# encoding: utf-8
class MyaccountController < ApplicationController
	before_filter :login_required
	
  def edit
  	@user = current_user
  end
  
  def update
	  @user = User.find(current_user.id)
  	if params[:user][:nick_name].blank?
  		flash.now[:notice] = "请输入你的名号"
  	else
			@user.update_attributes(params[:user])
			flash.now[:notice] = "设置更新成功"
		end
  	redirect_to account_path
  end
  
  def auth
  	@user = current_user
  end
  
  def update_user_name
  	@user = User.find(current_user.id)
  	user_name = params[:user][:user_name]
  	if user_name.blank?
  		return render 'auth'
  	end
  	
  	unless @user.user_name.blank?
  		flash.now[:error] = "已经设置过用户名，不可更改"
  		return render 'auth'
  	end
  	
  	if user_name =~ /^[a-zA-Z]\w+$/ && user_name.length <= 15
  		@user.update_attributes(params[:user])
			flash.now[:notice] = "设置更新成功"
			redirect_to auth_myaccount_path
		else
			flash.now[:error] = "永久username格式不正确。请看右边。"
  		return render 'auth'
  	end
  	
  end
  
	def submit_resetpassword
		return render update_email_myaccount_path if request.get?
		
  	new_pwd			= params[:user][:new_password]
  	repeat_pwd	= params[:user][:repeat_password]
  	
  	if new_pwd.size < 6
  		flash[:error] = "密码长度需要大于6"
  		return redirect_to resetpassword_myaccount_path
		elsif repeat_pwd != new_pwd
			flash[:error] = "两次输入密码不一样"
			return redirect_to resetpassword_myaccount_path
		end	
		
  	user = User.authenticate(current_user.email, params[:user][:password])
  	if user
  		flash[:notice] = "新密码设置成功"
    	user.reset_pwd(new_pwd)
		else 
			flash[:error] = "原始密码输入不正确"
  	end
  	
    redirect_to resetpassword_myaccount_path
	end  
	
	def update_email
		return render update_email_myaccount_path if request.get?
			
		new_email	= params[:user][:new_email]
		unless Utils.match_email?(new_email)
			flash[:error] = "请输入正确的email地址"
			return redirect_to resetemail_myaccount_path
		end
		
		if User.unique_email? new_email
			flash[:error] = "该email已被注册"
			return redirect_to resetemail_myaccount_path
		end
		
		user = User.authenticate(current_user.email, params[:user][:password])
		if user
			flash[:notice] = "新登录邮箱已设置成功"
			user.email = new_email
			user.save!
		else
			flash[:error] = "密码输入不正确"
		end
			
		redirect_to resetemail_myaccount_path
	end
	
	
end
